from flask import Blueprint, current_app, request
from flask_bcrypt import generate_password_hash, check_password_hash
from flask_restful import Resource
from flask_jwt_extended import create_access_token
import datetime
import sqlite3
from . import api_rest

class Login_admin(Resource):
    def post(self):
        body = request.get_json()
        username = body['username']
        password = body['password']
        authority = body['authority']
        
        conn = sqlite3.connect('backend/outbreak-management-system.db')
        c = conn.cursor()
        if (authority == 0): # 管理员
            order = "select USERNAME, PASSWORD from ADMINISTRATOR where USERNAME='" + username +"'"
        else:
            order = "select USERNAME, PASSWORD from PROPRIETOR where USERNAME='" + username +"'"
        c.execute(order)
        cursor = c.fetchall()
        # print(cursor)
        database_username = cursor[0][0]
        database_password = cursor[0][1]
        authorized = check_password_hash(database_password, password)
        if not authorized:
            return {'error':'Username or password error.'}, 401
        expires = datetime.timedelta(days=7)
        access_token = create_access_token(identity=[database_username, authority], expires_delta=expires)
        c.close()
        return {'token': access_token, 'username': database_username}, 200

       

api_rest.add_resource(Login_admin, '/login')